//
//  GLMusicListViewController.m
//  GLMusicBox
//
//  Created by 高磊 on 2017/10/26.
//  Copyright © 2017年 高磊. All rights reserved.
//

#import "GLMusicListViewController.h"
#import "LXArtistViewController.h"
#import "LXSongsViewController.h"
#import "LXEQViewController.h"
#import "ZYPlayingViewController.h"
#import "GLMiniMusicView.h"
#import "ZYMusicTool.h"
#import <MediaPlayer/MediaPlayer.h>

#import "LXSlideSelectionView.h"

@interface GLMusicListViewController () <LXSlideSelectionViewDelegate, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, GLMiniMusicViewDelegate, ZYPlayingViewControllerDelegate>
{
    
}

@property (nonatomic, strong) LXArtistViewController *artistVC;
@property (nonatomic, strong) LXSongsViewController *songVC;
@property (nonatomic, strong) LXEQViewController *eqVC;
@property (nonatomic, strong) LXSlideSelectionView *topSlideView;
@property (nonatomic, strong) NSMutableArray *songArr;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) ZYPlayingViewController *zyVC;
@property (nonatomic, assign) BOOL isFirstLoad;

@end

@implementation GLMusicListViewController

#pragma mark -  public method
- (void)selectPlayMusic:(ZYMusic *)music withAlbum:(NSString *)album
{
    if (self.searchBar != nil) {
        [self.searchBar removeFromSuperview];
    }
    [UIView animateWithDuration:0.5 animations:^{
        self.zyVC.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
    [self.zyVC musicBegin:music];
    [[GLMiniMusicView shareInstance] showMinViewDetail];
    [[GLMiniMusicView shareInstance] hiddenView];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
}

- (void)showCurrentView:(ZYMusic *)music
{
    [UIView animateWithDuration:0.5 animations:^{
        self.zyVC.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
    [self.zyVC showPlayingView];
}
#pragma mark -  life cycle

- (void)dealloc
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initializationData];
    [self addNotification];
    
    [self loadUI];
    [self buildNavi];
    
    [self loadViewDatas];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.selectTypeButtons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = obj;
        if (idx == 0 && button.isSelected) {
            [[GLMiniMusicView shareInstance] showView];
        }
    }];
    [GLMiniMusicView shareInstance].delegate = self;
}

- (void)viewDidAppear:(BOOL)animated
{
    if (self.isFirstLoad) {
        [self.view.window addSubview:self.zyVC.view];
        [self requestAuthorizationForMediaLibrary];
        self.isFirstLoad = NO;
    }
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
//    [[GLMiniMusicView shareInstance] hiddenView];
}
#pragma mark -  over write

#pragma mark -  setter & getter

#pragma mark -  private method
- (void)initializationData
{
    self.isFirstLoad = YES;
    [self.selectTypeButtons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = obj;
        [button setBackgroundImage:[UIImage imageWithColor:[UIColor whiteColor]] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageWithColor:kAppSelectedColor] forState:UIControlStateSelected];
        if (idx == 0) {
            button.selected = YES;
        }
    }];
}

- (void)loadUI
{
    self.view.backgroundColor = kAppLightBackgroundColor;
    
    self.artistVC = [[LXArtistViewController alloc] initWithNibName:NSStringFromClass([LXArtistViewController class]) bundle:nil];
    self.artistVC.title = @"ARTIST";
    self.artistVC.containerController = self;
    
    self.songVC = [[LXSongsViewController alloc] initWithNibName:NSStringFromClass([LXSongsViewController class]) bundle:nil];
    self.songVC.title = @"SONGS";
    self.songVC.containerController = self;
    
    self.eqVC = [[LXEQViewController alloc] initWithNibName:NSStringFromClass([LXEQViewController class]) bundle:nil];
    self.eqVC.title = @"EQ";
    self.eqVC.containerController = self;
    
    NSArray *vcList = @[self.artistVC, self.songVC, self.eqVC];
    [self setupSlider:vcList];
    
    self.typeBoardView.hidden = YES;
    self.typeDetailLabel.numberOfLines = 2;
    self.typeDetailLabel.lineBreakMode = NSLineBreakByTruncatingTail;
}

- (void)loadViewDatas
{
    
}

- (void)buildNavi
{
    UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    [button setImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(searchBarDown:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *searchBar = [[UIBarButtonItem alloc] initWithCustomView:button];
    self.navigationItem.rightBarButtonItem = searchBar;
}

- (void)setupSlider:(NSArray *)listControllers
{
    _topSlideView = [[LXSlideSelectionView alloc] init];
    _topSlideView.topViewHeight = 44;
    _topSlideView.textFont = [UIFont lx_systemFontOfSize:17];
    _topSlideView.backgroundColor = [UIColor whiteColor];
    _topSlideView.maxEqualCount = listControllers.count;
    _topSlideView.lineColor = kAppNormalTextColor;
    _topSlideView.viewControllers = listControllers;
    _topSlideView.delegate = self;

    [self.view addSubview:_topSlideView];
    [_topSlideView buildUI];
    
    CGFloat offset;
    NSString *version = [UIDevice currentDevice].systemVersion;
    if ([version compare:@"11.0"] != NSOrderedAscending) {//iOS系统版本 >= 11.0,不等于升序,就是等于和降序
        offset = 55;
    }else{
        offset = 44;
    }
    [_topSlideView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.boarderView.mas_bottom);
    }];
}

// MARK:- 判断是否有权限
- (void)requestAuthorizationForMediaLibrary {
    __weak typeof(self) weakSelf = self;
    // 请求媒体资料库权限
    MPMediaLibraryAuthorizationStatus authStatus = [MPMediaLibrary authorizationStatus];
    
    if (authStatus != MPMediaLibraryAuthorizationStatusAuthorized) {
        [MPMediaLibrary requestAuthorization:^(MPMediaLibraryAuthorizationStatus status) {
            if (status == MPMediaLibraryAuthorizationStatusAuthorized) {
                [weakSelf getItunesMusic];
            }
        }];
    } else {
        [self getItunesMusic];
    }
}

- (void)getItunesMusic {
    dispatch_async(dispatch_get_main_queue(), ^{
        [EasyLoadingView showLoadingText:@"Loading songs, please wait moment!"];
    });
    NSArray *array = [ZYMusicTool musics];
    NSDictionary *dic = [ZYMusicTool aritstMusics];
    self.songVC.musicListArray = [[NSMutableArray alloc] initWithArray:array];
    self.artistVC.artistsListDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
    dispatch_async(dispatch_get_main_queue(), ^{
        [EasyLoadingView hidenLoading];
    });
}

- (void)radioStyle:(NSInteger)index
{
    UInt8 data[3];
    data[0] = 0x02;
    data[1] = index & 0xff;
    data[2] = 0x00;
    [[BLETransDeviceSingleton sharedInstance] characteristc:COMMON_CHARACTERISTIC_UUID sendHostCmd:data lenght:3];
}

#pragma mark -  notification
- (void)addNotification
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(bleDataReceive:) name:kAppDidAssociateDeviceString object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reload) name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil];
}

-(void)bleDataReceive:(NSNotification *)notification
{
    NSData *data = notification.userInfo[kAppHeadUnitData];
    Byte *MessageBt = (Byte *)[data bytes];
    NSInteger comandStatus = (MessageBt[0] << 8) + MessageBt[1];
}

- (void)reload
{
    [[GLMiniMusicView shareInstance] showMinViewDetail];
    [self.songVC musicScrollTo];
}
#pragma mark -  network

#pragma mark -  event handle
- (void)searchBarDown:(UIBarButtonItem *)sender
{
    self.navigationItem.rightBarButtonItem.enabled = NO;
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44)];
    self.searchBar.alpha = 0;
    self.searchBar.delegate = self;
    [self.searchBar becomeFirstResponder];
    self.searchBar.showsCancelButton = YES;
    [self.view addSubview:self.searchBar];
    
    for (id obj in [self.searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    [btn setTitle:@"" forState:UIControlStateNormal];
                    btn.tintColor = kAppNormalTextColor;
                    [btn setImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
                }
            }
        }
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        self.searchBar.frame = CGRectMake(0, 0, kScreenWidth, 44);
        self.searchBar.alpha = 1;
    }];
}

- (IBAction)typeSelectDown:(UIButton *)sender {
    [self.selectTypeButtons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = obj;
        button.selected = NO;
    }];
    sender.selected = YES;
    if (sender.tag != 0) {
        self.typeBoardView.hidden = NO;
        [[GLMiniMusicView shareInstance] hiddenView];
        [self.view bringSubviewToFront:self.typeBoardView];
        switch (sender.tag) {
            case 1:
                self.typeNameLabel.text = @"USB Connected";
                self.typeDetailLabel.text = @"Your device is now playing via USB";
                self.typeImageView.image = [UIImage imageNamed:@"usbBig"];
                [self radioStyle:3];
                break;
                
            case 2:
                self.typeNameLabel.text = @"FM Connected";
                self.typeDetailLabel.text = @"Your device is now playing via FM";
                self.typeImageView.image = [UIImage imageNamed:@"fmBig"];
                [self radioStyle:1];
                break;
                
            case 3:
                self.typeNameLabel.text = @"AUX Connected";
                self.typeDetailLabel.text = @"Your device is now playing via AUX";
                self.typeImageView.image = [UIImage imageNamed:@"auxBig"];
                [self radioStyle:2];
                break;
            default:
                break;
        }
    } else {
        self.typeBoardView.hidden = YES;
        [[GLMiniMusicView shareInstance] showView];
        [self radioStyle:4];
    }
}

#pragma mark -  delegate
#pragma BLETransDeviceSingletonDelegate
- (void)BLETransDeviceSingletonConnected:(BOOL)connected
{
    
}

#pragma LXSlideSelectionViewDelegate
- (void)slideView:(LXSlideSelectionView *)slideView willShowPageAtIndex:(NSInteger)index
{
    self.selectIndex = index;
    if (index == 2) {
        self.navigationItem.rightBarButtonItem.enabled = NO;
    } else {
        self.navigationItem.rightBarButtonItem.enabled = YES;
    }
}

- (void)slideView:(LXSlideSelectionView *)slideView willLeavePageAtIndex:(NSInteger)index
{
    
}

#pragma UISearchBarDelegate
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (self.selectIndex == 0) {
        self.artistVC.searchString = searchText;
    } else if (self.selectIndex == 1) {
        self.songVC.searchString = searchText;
    }
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar removeFromSuperview];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    if (self.selectIndex == 0) {
        self.artistVC.cancelSearch = YES;
    } else if (self.selectIndex == 1) {
        self.songVC.cancelSearch = YES;
    }
}

#pragma GLMusicMinViewDelegate
- (void)miniMusicView:(GLMiniMusicView *)musicView tapDown:(UIGestureRecognizer *)gesture
{
    [UIView animateWithDuration:0.5 animations:^{
        self.zyVC.view.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    }];
    [self.zyVC showPlayingView];
    [[GLMiniMusicView shareInstance] hiddenView];
}

- (void)miniMusicViewNext:(GLMiniMusicView *)musicView
{
    
}
#pragma ZYPlayingViewControllerDelegate
- (void)playingViewControllerExit:(ZYPlayingViewController *)zyPlayVC
{
    [[GLMiniMusicView shareInstance] showView];
}
#pragma mark -  lazy load
-(NSMutableArray *)songArr {
    if (!_songArr) {
        _songArr = [[NSMutableArray alloc] init];
    }
    return _songArr;
}

- (ZYPlayingViewController *)zyVC {
    if (!_zyVC) {
        _zyVC = [[ZYPlayingViewController alloc] initWithNibName:NSStringFromClass([ZYPlayingViewController class]) bundle:nil];
        _zyVC.view.frame = CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight);
        _zyVC.delegate = self;
    }
    return _zyVC;
}
#pragma mark -  memoryWarning
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
